package com.ruoyi.map.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cyl.h5.domain.vo.RecentlyBuyCVo;
import com.cyl.h5.domain.vo.RecentlyBuyVo;
import com.cyl.manager.oms.domain.entity.OrderItem;
import com.cyl.manager.pms.domain.entity.PmsBrandAttention;
import com.cyl.manager.pms.domain.entity.Sku;
import com.cyl.manager.pms.domain.query.BrandQuery;
import com.cyl.manager.pms.domain.vo.SkuVO;
import com.cyl.manager.pms.mapper.BrandMapper;
import com.cyl.manager.pms.mapper.PmsBrandAttentionMapper;
import com.cyl.manager.pms.mapper.SkuMapper;
import com.cyl.manager.ums.domain.entity.UserInfo;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.github.pagehelper.PageHelper;
import com.jhlabs.image.Histogram;
import com.ruoyi.common.constant.Constants;
import com.ruoyi.framework.config.LocalDataUtil;
import com.ruoyi.map.domain.PmsHistory;
import com.ruoyi.map.domain.PmsProduct;
import com.ruoyi.map.dto.PmsProductDTO;
import com.ruoyi.map.mapper.PmsHistoryMapper;
import com.ruoyi.map.mapper.PmsProductMapper;
import com.ruoyi.map.query.PmsProductQuery;
import com.ruoyi.map.service.IPmsProductService;
import com.ruoyi.web.core.config.LocalUserInfoUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

import static com.ruoyi.framework.datasource.DynamicDataSourceContextHolder.log;

/**
 * @author sangsijing
 * @since 2025/5/8 16:35
 */
@Service
public class PmsProductServiceImpl implements IPmsProductService {

    @Autowired
    private PmsProductMapper productMapper;

    @Autowired
    private PmsHistoryMapper pmsHistoryMapper ;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private PmsBrandAttentionMapper brandAttentionMapper;

    @Override
    public List<PmsProduct> getList() {
        return productMapper.getList();
    }

    @Override
    public List<PmsProductDTO> promotionList() {
        return productMapper.promotionList();
    }

    @Override
    public PmsProductDTO productDetails(Long id) {
        // 查询 sku 信息
        Sku sku = new Sku();
        sku.setProductId(id);
        List<SkuVO> skus = skuMapper.selectByEntity(sku);
        ObjectMapper objectMapper = new ObjectMapper();

        for (SkuVO skuItem : skus) {
            String spData = skuItem.getSpData();
            if (spData != null && !spData.isEmpty()) {
                try {
                    // 1. 解析 JSON 字符串成 Map<String, String>
                    Map<String, String> spDataMap = objectMapper.readValue(
                            spData,
                            new TypeReference<Map<String, String>>() {}
                    );

                    // 2. 转换成 List<Map<String, String>>，格式：[{"key":"款式", "value":"蝴蝶富士1.68米"}, ...]
                    List<Map<String, String>> skuSpecList = spDataMap.entrySet().stream()
                            .map(entry -> {
                                Map<String, String> specEntry = new HashMap<>();
                                specEntry.put("key", entry.getKey());
                                specEntry.put("value", entry.getValue());
                                return specEntry;
                            })
                            .collect(Collectors.toList());

                    // 3. 设置到当前 skuItem 的 skuList 字段
                    skuItem.setSkuList(skuSpecList);
                } catch (Exception e) {
                    e.printStackTrace(); // 处理 JSON 解析错误
                    skuItem.setSkuList(Collections.emptyList()); // 解析失败时设为空 List
                }
            } else {
                skuItem.setSkuList(Collections.emptyList()); // spData 为空时设为空 List
            }
        }

        // 设置到 DTO
        PmsProductDTO pmsProductDTO = productMapper.productDetails(id);
        pmsProductDTO.setSkus(skus);

        return pmsProductDTO;
    }

    @Override
    public List<PmsProductDTO> getRecommendList(PmsProductDTO pmsProduct,Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        return productMapper.getRecommendList(pmsProduct);
    }


    /**
     * 查询商品表列表
     *
     * @param query 查询条件
     * @param page 分页条件
     * @return 商品表
     */
    @Override
    public List<PmsProduct> selectList(PmsProductQuery query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        QueryWrapper<PmsProduct> qw = new QueryWrapper<>();
        String fishingType = query.getFishingType();
        if (!StringUtils.isEmpty(fishingType)) {
            qw.eq("fishing_type", fishingType);
        }
        Long brandId = query.getBrandId();
        if (brandId != null) {
            qw.eq("brand_id", brandId);
        }
        Long categoryId = query.getCategoryId();
        if (categoryId != null) {
            qw.eq("category_id", categoryId);
        }
        String nameLike = query.getNameLike();
        if (!StringUtils.isEmpty(nameLike)) {
            qw.like("name", nameLike);
        }
        String pic = query.getPic();
        if (!StringUtils.isEmpty(pic)) {
            qw.eq("pic", pic);
        }
        String albumPics = query.getAlbumPics();
        if (!StringUtils.isEmpty(albumPics)) {
            qw.eq("album_pics", albumPics);
        }
        Integer publishStatus = query.getPublishStatus();
        if (publishStatus != null) {
            qw.eq("publish_status", publishStatus);
        }
        Long promotionStatus = query.getPromotionStatus();
        if (promotionStatus != null) {
            qw.eq("promotion_status", promotionStatus);
        }
        return productMapper.selectList(qw);
    }

    @Override
    public List<PmsProductDTO> productSearch(PmsProductDTO query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        String name = query.getName();
        if (!StringUtils.isEmpty(name)){
            //获取当前用户id
            Long userId = LocalUserInfoUtil.getLocalUserInfo().getId();
            PmsHistory history = new PmsHistory();
            history.setUserId(userId);
            history.setHistoryName(name);
            pmsHistoryMapper.insert(history);
        }
        return productMapper.productSearch(query);
    }

    @Override
    public List<PmsProductDTO> recommend(PmsProductDTO query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        return productMapper.recommend();
    }

    @Override
    public List<PmsProductDTO> brandProductList(PmsProductDTO query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        UserInfo member = (UserInfo) LocalDataUtil.getVar(Constants.MEMBER_INFO);
        //根据品牌id查询商品
        List<PmsProductDTO> list = productMapper.brandProductList(query);
        if (list == null || list.size() == 0){
            return list;
        }
        //构造查询条件
        PmsBrandAttention pmsBrandAttention = new PmsBrandAttention();
        pmsBrandAttention.setBrandId(list.get(0).getBrandId());
        pmsBrandAttention.setUserId(member.getId());
        //根据品牌id查询品牌关注信息
        List<PmsBrandAttention> pmsBrandAttentions = brandAttentionMapper.selectByEntity(pmsBrandAttention);
        String follower = pmsBrandAttentions.isEmpty() ? "0" : pmsBrandAttentions.get(0).getFollower();
        list.forEach(pmsProductDTO -> pmsProductDTO.setFollower(follower));
        return list;
    }

    @Override
    public List<RecentlyBuyCVo> recentlys(OrderItem query, Pageable page) {
        if (page != null) {
            PageHelper.startPage(page.getPageNumber() + 1, page.getPageSize());
        }
        List<RecentlyBuyCVo> orderItems = productMapper.recentlys(query);
        ObjectMapper objectMapper = new ObjectMapper();
        orderItems.forEach(item -> {
            String spData = item.getSpData();
            if (com.ruoyi.common.utils.StringUtils.isNotBlank(spData)) {
                try {
                    Map<String, String> spDataMap = objectMapper.readValue(
                            spData,
                            new TypeReference<Map<String, String>>() {}
                    );

                    List<Map<String, String>> skuSpecList = spDataMap.entrySet().stream()
                            .map(entry -> {
                                Map<String, String> specEntry = new HashMap<>();
                                specEntry.put("key", entry.getKey());
                                specEntry.put("value", entry.getValue());
                                return specEntry;
                            })
                            .collect(Collectors.toList());

                    item.setSkuList(skuSpecList);
                } catch (Exception e) {
                    log.error("解析spData失败: {}", spData, e);
                    item.setSkuList(Collections.emptyList());
                }
            } else {
                item.setSkuList(Collections.emptyList());
            }
        });

        return orderItems;
    }


    @Override
    public List<Map<String, String>> paramsJson(Long id) {
        PmsProduct pmsProduct = productMapper.selectById(id);
        ObjectMapper objectMapper = new ObjectMapper();
        String paramsJson = pmsProduct.getParamsJson();

        try {
            //解析字符串
            List<Map<String, Object>> originalList = objectMapper.readValue(
                    paramsJson,
                    new TypeReference<List<Map<String, Object>>>() {}
            );
            //转换成 List<Map<String, String>>，格式：[{"key":"款式", "value":"蝴蝶富士1.68米"}, ...]
            return originalList.stream()
                    .map(item -> {
                        Map<String, String> newItem = new HashMap<>();
                        newItem.put("key", item.get("name").toString());
                        newItem.put("value", item.get("content").toString());
                        return newItem;
                    })
                    .collect(Collectors.toList());

        } catch (Exception e) {
            log.error("JSON 转换失败", e);
            return Collections.emptyList();
        }


    }

}
